import { TIMES } from '@/config';
import { clickByBounds, clickByDesc, clickByText } from '@/utils/clickManager';
import getDouyinScheme from '@/utils/getDouyinScheme';
import LogManager from '@/utils/LogManager';
import Application from './Application';

class LiveRoom {
  imageQuality = false;
  direction: '上' | '下' = '下';
  currentLiveCount = 0;
  /** 记录直播间 */
  private recordLive = {
    name: '',
    people: 0,
    switchCount: 0,
  };
  readonly readonlyRecordLive = { ...this.recordLive };

  private peopleNumberNodeMatch = /.*在线观众/;

  private log(value: any) {
    LogManager.add(`[直播间]\t${value}`);
  }

  /**
   * 当前直播间名称
   * 直播间的账号名称
   */
  get nameNode() {
    return id('user_name').findOne(TIMES.LIVEROOM_FIND_NODE_TIMEOUT_SHORT);
  }

  /** 读取记录直播间值 */
  get getRecordLive() {
    return this.recordLive;
  }

  /** 直播间人数节点 */
  get peopleNumberNode() {
    // return descMatches(this.peopleNumberNodeMatch).findOne(TIMES.LIVEROOM_FIND_NODE_TIMEOUT_SHORT);
    return id('oo4').findOne(TIMES.LIVEROOM_FIND_NODE_TIMEOUT_SHORT);
  }

  /**
   * 直播间人数
   * 处理后的数字
   * @returns 10万+ = 110000
   */
  get peopleNumber(): number {
    if (!this.peopleNumberNode) {
      this.log('未找到直播人数节点');
      return 0;
    }

    const text = this.peopleNumberNode.text();
    let count = 0;

    // 10万+
    if (text.indexOf('+') !== -1) {
      return 110000;
    }

    // 处理万
    if (text.indexOf('万')) {
      count = Number(text.replace('万', '0000'));
    }

    return count;
  }

  /** 设置记录直播间值 */
  setRecordLive<K extends keyof typeof this.recordLive>(key: K, value: (typeof this.recordLive)[K]) {
    this.recordLive[key] = value;
  }

  /** 更新记录当前直播间值 */
  updateCurrentLive() {
    this.setRecordLive('name', this.nameNode?.text() || '');
    this.setRecordLive('people', this.peopleNumber);
    this.setRecordLive('switchCount', 0);
  }

  /** 重置记录当前直播间值 */
  resetCurrentLive() {
    this.recordLive = this.readonlyRecordLive;
  }

  /** 是否在直播间 */
  get isLive(): boolean {
    const activity = currentActivity();

    const arr = [this.nameNode, activity === 'com.ss.android.ugc.aweme.live.LivePlayActivity', activity === 'com.bytedance.android.annie.dialog.NoMarginSheetBaseDialog'];

    return arr.some(item => item);
  }

  /** 直播是否结束 */
  get isEnd(): boolean {
    const endNode = text('直播已结束').findOne(TIMES.LIVEROOM_SLEEP_SHORT);
    endNode && this.log('直播已结束');
    return Boolean(endNode);
  }

  /** 是否直播间替换 */
  get isSwitchover(): boolean {
    return this.nameNode?.text() !== this.getRecordLive.name;
  }

  /** 点赞 */
  doubleLike(count: number = 5): void {
    let screenHeight = device.height;
    let screenWidth = device.width;
    for (let i = 0; i < count; i++) {
      click(screenWidth / 2, screenHeight / 2);
      sleep(100);
    }

    this.log('点赞完毕！');
  }

  /** 调整图像品质 - 标清画质  */
  tuningImageQuality(): void {
    clickByDesc('更多面板 按钮');
    sleep(TIMES.LIVEROOM_SLEEP_SHORT);

    clickByText('清晰度');
    sleep(TIMES.LIVEROOM_SLEEP_SHORT);

    const standard = descMatches(/标清按钮|已选中 标清按钮/).findOne(TIMES.LIVEROOM_FIND_NODE_TIMEOUT_SHORT)!;
    const isClickStandard = clickByBounds(standard);
    sleep(TIMES.LIVEROOM_SLEEP_SHORT);
    this.log(`${isClickStandard ? '画质调整 标清' : '画质调整失败'}`);
    this.imageQuality = true;
  }

  /**
   * 上下滑动
   * 上：下滑
   * 下：上滑
   */
  swipeToLive(mode: '上' | '下'): void {
    try {
      const screenHeight = device.height;
      const screenWidth = device.width;

      this.log(`${mode}一个直播间`);
      if (mode === '上') {
        swipe(screenWidth / 2, screenHeight * 0.2, screenWidth / 2, screenHeight * 0.8, 200);
      } else {
        swipe(screenWidth / 2, screenHeight * 0.8, screenWidth / 2, screenHeight * 0.2, 200);
      }

      this.setRecordLive('switchCount', this.recordLive.switchCount + 1);

      sleep(1000); // 等待切换完成
    } catch (error: any) {
      this.log('滑动失败: ' + error.message);
    }
  }

  /** 进入超级福袋直播间 */
  enterAllLive(): void {
    const query = '超级福袋直播间';
    const searchUrl = `${getDouyinScheme()}://search`;
    app.startActivity({
      action: 'android.intent.action.VIEW',
      data: searchUrl,
    });

    sleep(TIMES.LIVEROOM_SLEEP_SHORT);

    const searchNode = id('et_search_kw').findOne(TIMES.LIVEROOM_FIND_NODE_TIMEOUT_SHORT);
    sleep(TIMES.LIVEROOM_SLEEP_SHORT);
    searchNode?.setText(query);
    
    sleep(TIMES.LIVEROOM_SLEEP_SHORT);
    clickByDesc('搜索');
    sleep(TIMES.LIVEROOM_SLEEP_LONE);
    clickByText('直播');
    sleep(TIMES.LIVEROOM_SLEEP_LONE);
    click(device.width / 2, device.height / 2);

    sleep(TIMES.LIVEROOM_SLEEP_LONE);

    if (this.isLive) {
      sleep(TIMES.LIVEROOM_SLEEP_LONE);
      this.tuningImageQuality();
      sleep(TIMES.LIVEROOM_SLEEP_LONE);
      this.doubleLike(10);
      sleep(TIMES.LIVEROOM_SLEEP_SHORT);
    }
  }

  /** 进入关注主播的直播间 */
  enterConcernLive(): void {
    if (this.isLive) {
      back();
      sleep(TIMES.LIVEROOM_SLEEP_LONE);
    }
    launchApp(Application.douyinVersion);
    sleep(TIMES.LIVEROOM_SLEEP_LONE);
    clickByDesc('我，按钮');
    sleep(TIMES.LIVEROOM_SLEEP_SHORT);
    clickByText('关注');
    sleep(TIMES.LIVEROOM_SLEEP_SHORT);
    clickByText('直播');
    clickByText('直播中');
    sleep(TIMES.LIVEROOM_SLEEP_LONE);
    clickByText('直播中');

    const firstStudioNode = className('androidx.recyclerview.widget.RecyclerView').findOne(TIMES.LIVEROOM_FIND_NODE_TIMEOUT_LONG)?.children()[1];
    if (!firstStudioNode) {
      this.log('开播人数为 0');
      return;
    }
    clickByBounds(firstStudioNode);

    sleep(TIMES.LIVEROOM_SLEEP_LONE);
    this.tuningImageQuality();
    sleep(TIMES.LIVEROOM_SLEEP_LONE);
    this.doubleLike(10);
    sleep(TIMES.LIVEROOM_SLEEP_SHORT);
  }
}

export default new LiveRoom();
